document.addEventListener('DOMContentLoaded', function () {

    checkLoginAndProceed(() =>{
        console.log("用户已登录")
    });

    const ConfigDate = {
        _data:{
            goodsId: "9890001",
            activityId: null,
            source: "s01",
            channel: "c01"
        },

        setData(data){
            this._data.activityId = data.activity.activityId;
        },

        getGoodsId(){
            return this._data.goodsId;
        },

        getActivityId(){
            return this._data.activityId;
        },

        getSource(){
            return this._data.source;
        },

        getChannel(){
            return this._data.channel;
        }
    }

    const LockTradeOrderData = {
        _data:{
            orderId: null,
            outTradeNo: null
        },
        init(data) {
            this._data.orderId = data.orderId
            this._data.outTradeNo = data.outTradeNo
        },
        getOrderId(){
            return this._data.orderId
        },

        getOutTradeNo(){
            return this._data.outTradeNo
        }
    }


    // 轮播图逻辑
    const swiperWrapper = document.querySelector('.swiper-wrapper');
    const swiperDots = document.querySelectorAll('.swiper-dot');
    let currentIndex = 0;

    function updateSwiper() {
        swiperWrapper.style.transform = `translateX(-${currentIndex * 100}%)`;

        swiperDots.forEach((dot, index) => {
            dot.classList.toggle('active', index === currentIndex);
        });
    }

    // 自动轮播
    setInterval(() => {
        currentIndex = (currentIndex + 1) % 3;
        updateSwiper();
    }, 3000);


    // 倒计时逻辑
    function updateCountdowns() {
        const countdownElements = document.querySelectorAll('.countdown');

        countdownElements.forEach(element => {
            let time = parseInt(element.getAttribute('data-time'));
            if (time > 0) {
                time--;
                element.setAttribute('data-time', time);
                element.textContent = msToTime(time * 1000);
            } else {
                element.textContent = '已结束';
                element.style.color = '#999';
            }
        });
    }

    setInterval(updateCountdowns, 1000);

    // 按钮事件处理
    const joinButtons = document.querySelectorAll('.join-btn');
    const soloBuyButton = document.getElementById('solo-buy');
    const groupBuyButton = document.getElementById('group-buy');
    const paymentPage = document.getElementById('payment-page');
    const cancelPaymentButton = document.getElementById('cancel-payment');
    const confirmPaymentButton = document.getElementById('confirm-payment');
    const loginOverlay = document.getElementById('login-overlay');
    const loginForm = document.getElementById('login-form');
    const loading = document.getElementById('loading');
    const loginCloseBtn = document.getElementById('login-close-btn');

    /*登录方法定义*/
    // 登录表单提交事件
    loginForm.addEventListener('submit', function (e) {
        e.preventDefault();

        const loginUsername = document.getElementById('login-username').value;
        const loginPassword = document.getElementById('login-password').value;
        let isValid = true;
        let errorMessage = '';

        // 验证用户名
        if (!loginUsername) {
            errorMessage = '请输入用户名';
            isValid = false;
        } else if (!validateUsername(loginUsername)) {
            errorMessage = '用户名只能是中文、英文、数字的组合';
            isValid = false;
        } else {
            document.getElementById('login-username-error').style.display = 'none';
        }

        // 验证密码
        if (!loginPassword) {
            if (errorMessage) {
                errorMessage = '请输入用户名和密码';
            } else {
                errorMessage = '请输入密码';
            }
            isValid = false;
        } else if (!validatePassword(loginPassword)) {
            if (errorMessage) {
                errorMessage = '用户名格式错误，密码必须是6位数字';
            } else {
                errorMessage = '密码必须是6位数字';
            }
            isValid = false;
        } else {
            document.getElementById('login-password-error').style.display = 'none';
        }

        if (!isValid) {
            // 显示Toast提示
            showToast(errorMessage);
            return;
        }

        // 保存登录信息到cookie
        setCookie('user', JSON.stringify({username: loginUsername}), 7);

        // 隐藏登录弹窗
        hideLoginOverlay();
        // 重新获取商品信息
        showLoading();
        fetchGoodsInfo(loginUsername, ConfigDate).finally(() => {
            hideLoading();
        });
        // 刷新页面（模拟登录后状态）
        location.reload();
        // 显示成功提示
        showToast('登录成功！');
    });

    // 点击登录弹窗外部关闭弹窗
    loginOverlay.addEventListener('click', function(e) {
        if (e.target === loginOverlay) {
            hideLoginOverlay();
        }
    });

    // 输入时实时验证
    document.getElementById('login-username').addEventListener('input', function() {
        if (validateUsername(this.value)) {
            document.getElementById('login-username-error').style.display = 'none';
        }
    });

    document.getElementById('login-password').addEventListener('input', function() {
        if (validatePassword(this.value)) {
            document.getElementById('login-password-error').style.display = 'none';
        }
    });

    // 显示Toast提示
    function showToast(message, shakeFlag = true) {
        const toast = document.getElementById('login-toast');
        toast.textContent = message;
        toast.style.display = 'block';
        if (shakeFlag) {
            toast.classList.add('shake');
        }

        // 3秒后隐藏Toast
        setTimeout(() => {
            toast.style.display = 'none';
            toast.classList.remove('shake');
        }, 3000);
    }

    // 登录关闭按钮点击事件
    loginCloseBtn.addEventListener('click', function() {
        hideLoginOverlay();
    });

    // Cookie操作函数
    function setCookie(name, value, days) {
        let expires = "";
        if (days) {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "") + expires + "; path=/";
    }

    function getCookie(name) {
        console.log("检查cookie ", name)
        const nameEQ = name + "=";
        const ca = document.cookie.split(';');
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    function eraseCookie(name) {
        document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }

    // 检查登录状态
    function checkLogin() {
        return getCookie("user") !== null;
    }

    // 验证用户名格式
    function validateUsername(username) {
        const regex = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
        return regex.test(username);
    }

    // 验证密码格式
    function validatePassword(password) {
        const regex = /^\d{6}$/;
        return regex.test(password);
    }

    // 显示登录页面
    function showLoginOverlay() {
        loginOverlay.style.display = 'flex';
    }

    // 隐藏登录弹窗
    function hideLoginOverlay() {
        loginOverlay.style.display = 'none';
    }


    /*首页方法定义*/
    // 显示加载提示
    function showLoading() {
        loading.style.display = 'flex';
    }

    // 隐藏加载提示
    function hideLoading() {
        loading.style.display = 'none';
    }

    // 模拟API请求
    function mockApiRequest(url, data = null) {
        return new Promise((resolve) => {
            setTimeout(() => {
                console.log(`请求API: ${url}`, data);
                resolve({success: true, message: '操作成功'});
            }, 1000);
        });
    }
    // 实际请求API
    function requestApi(url, data) {
        console.info("请求API ", url, "数据 ", data)
        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
    }

    /*支付方法定义*/
    // 显示支付页面
    function showPaymentPage() {
        paymentPage.style.display = 'flex';
    }

    // 隐藏支付页面
    function hidePaymentPage() {
        paymentPage.style.display = 'none';
    }

    // 检查登录状态并执行操作
    function checkLoginAndProceed(callback) {
        var checkLoginResult = checkLogin();
        console.log("检查登录结果 ", checkLoginResult)
        if (checkLoginResult) {
            callback();
        } else {
            showLoginOverlay();
        }
    }

    // 立即抢单按钮点击事件
    joinButtons.forEach(button => {
        button.addEventListener('click', function () {
            checkLoginAndProceed(() => {
                requestLockGroupApi(this.getAttribute('data-group'));
                this.getAttribute("")
            });
        });
    });

    // 单独购买按钮点击事件
    soloBuyButton.addEventListener('click', function () {
        checkLoginAndProceed(() => {
            showPaymentPage();
        });
    });

    // 开团购买按钮点击事件
    groupBuyButton.addEventListener('click', function () {
        checkLoginAndProceed(() => {
            showLoading();

            mockApiRequest('http://127.0.0.1/market/3')
                .then(result => {
                    hideLoading();
                    if (result.success) {
                        showPaymentPage();
                    } else {
                        alert('开团失败，请重试');
                    }
                });
        });
    });

    // 取消支付按钮点击事件
    cancelPaymentButton.addEventListener('click', function () {
        hidePaymentPage();
    });

    // 支付完成按钮点击事件
    confirmPaymentButton.addEventListener('click', function () {
        showLoading();

        requestSettlementGroupApi();
        mockApiRequest('http://127.0.0.1/market/4')
            .then(result => {
                hideLoading();
                hidePaymentPage();
                if (result.success) {
                    alert('支付成功！');
                } else {
                    alert('支付失败，请重试');
                }
            });
    });

    // 将毫秒转换为HH:MM:SS格式
    function msToTime(ms) {
        if (!ms || ms <= 0) return "00:00:00";

        const seconds = Math.floor(ms / 1000);
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;

        return [
            hours.toString().padStart(2, '0'),
            minutes.toString().padStart(2, '0'),
            secs.toString().padStart(2, '0')
        ].join(':');
    }

    // 从毫秒转换为秒（用于倒计时）
    function msToSeconds(ms) {
        return Math.floor(ms / 1000);
    }

    function getUserId(){
        const userCookie = getCookie("user");
        let userId = "";

        if (userCookie) {
            try {
                const userData = JSON.parse(userCookie);
                userId = userData.username || "";
            } catch (e) {
                console.error("解析用户Cookie失败", e);
            }
        }
        return userId;
    }

    // 请求API获取商品信息
    async function fetchGoodsInfo(userId, configData) {

        const requestData = {
            userId: userId,
            goodsId: configData.getGoodsId(),
            source: configData.getSource(),
            channel: ConfigDate.getChannel()
        };

        try {
            const response = await fetch('http://127.0.0.1:8091/api/v1/group-buy-market/home-page/query_goods_group_buy_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            });

            const data = await response.json();

            if (data.code === "E0000") {
                // 成功获取数据，更新页面
                updatePageWithData(data.data);
            } else {
                // 显示错误信息
                showToast(data.info || "请求失败");
            }
        } catch (error) {
            console.error("API请求失败:", error);
            showToast("网络错误，请稍后重试");

            // 如果API请求失败，使用模拟数据
            useMockData();
        }
    }

    // 使用模拟数据
    function useMockData() {
        const mockData = {
            goods: {
                goodsId: "9890001",
                originalPrice: 100.00,
                deductionPrice: 20,
                payPrice: 80.00,
                goodsName: "《手写MyBatis：渐进式源码实践》"
            },
            teamStatistic: {
                allTeamCount: 2,
                allTeamCompleteCount: 0,
                allTeamUserCount: 76
            },
            teamList: [
                {
                    teamId: "75218722",
                    teamName: "小傅哥",
                    groupBuyEndTime: 1922869180000,
                    groupBuyEndLeftTime: 349000,
                    groupBuyStartTime: 1733566780000,
                    targetCount: 3,
                    completeCount: 1,
                    lockCount: 0
                },
                {
                    teamId: "75218723",
                    teamName: "李二狗",
                    groupBuyEndTime: 1922869180000,
                    groupBuyEndLeftTime: 349000,
                    groupBuyStartTime: 1733566780000,
                    targetCount: 3,
                    completeCount: 1,
                    lockCount: 0
                }
            ]
        };

        updatePageWithData(mockData);
    }

    // 使用API返回的数据更新页面
    function updatePageWithData(data) {
        console.log("更新页面数据:", data);
        // 更新商品信息
        document.getElementById('product-title').textContent = data.goods.goodsName;
        document.getElementById('promotion-text').textContent = `直降￥${data.goods.deductionPrice}，${data.teamStatistic.allTeamUserCount}人在抢，参与马上抢到`;
        document.getElementById('current-price').textContent = `￥${data.goods.payPrice}`;
        document.getElementById('original-price').textContent = `￥${data.goods.originalPrice}`;
        document.getElementById('payment-amount').textContent = `支付金额 ¥${data.goods.payPrice}`;

        // 初始化页面的拼团配置数据
        ConfigDate.setData(data)

        // 更新团队列表
        const groupList = document.getElementById('group-list');
        groupList.innerHTML = '';

        data.teamList.forEach((team, index) => {
            const teamItem = document.createElement('div');
            teamItem.className = 'group-item';

            // 获取名字的第一个字符作为头像
            const firstNameChar = team.teamName.charAt(0);

            teamItem.innerHTML = `
                    <div class="avatar">${firstNameChar}</div>
                    <div class="group-info">
                        <div class="group-name">${team.teamName}</div>
                        <div class="group-status">拼单即将结束</div>
                    </div>
                    <div class="group-action">
                        <div class="countdown" data-time="${msToSeconds(team.groupBuyEndLeftTime)}">${msToTime(team.groupBuyEndLeftTime)}</div>
                        <button class="join-btn" data-group="${team.teamId}">立即抢单</button>
                    </div>
                `;

            groupList.appendChild(teamItem);
        });

        // 重新绑定事件到新创建的按钮
        bindJoinButtons();
    }

    // 绑定立即抢单按钮事件
    function bindJoinButtons() {
        const joinButtons = document.querySelectorAll('.join-btn');
        joinButtons.forEach(button => {
            button.addEventListener('click', function() {
                checkLoginAndProceed(() => {
                    requestLockGroupApi(this.getAttribute('data-group'));
                });
            });
        });
    }

    function requestLockGroupApi(teamId){
        showLoading();

        const requestData = {
            userId: getUserId(),
            goodsId: ConfigDate.getGoodsId(),
            source: ConfigDate.getSource(),
            channel: ConfigDate.getChannel(),
            activityId: ConfigDate.getActivityId(),
            teamId: teamId
        };

        requestApi("http://127.0.0.1:8091/api/v1/group-buy-market/trade/lock_market_pay_order", requestData)
            .then(result =>(result.json()))
            .then(data => {
                hideLoading();
                console.log("请求锁单结果", data);
                if (data.code == "E0000") {
                    LockTradeOrderData.init(data.data)
                    showPaymentPage();
                }else {
                    // 显示错误信息
                    showToast(data.info || "请求失败");
                }
        })

    }

    function requestSettlementGroupApi(){
        showLoading();

        const requestData = {
            userId: getUserId(),
            source: ConfigDate.getSource(),
            channel: ConfigDate.getChannel(),
            outTradeNo: LockTradeOrderData.getOutTradeNo()
        };

        requestApi("http://127.0.0.1:8091/api/v1/group-buy-market/trade/settlement_market_pay_order", requestData)
            .then(result =>(result.json()))
            .then(data => {
                hideLoading();
                console.log("请求结算结果", data);
                if (data.code == "E0000") {
                    hidePaymentPage();
                    // 初始加载数据
                    showToast("结算成功", false);
                    // 显示错误信息
                    showToast(data.info || "请求失败");
                    fetchGoodsInfo(getUserId(), ConfigDate).finally(() => {
                        hideLoading();
                    });
                }else {
                    // 显示错误信息
                    showToast(data.info || "请求失败");
                }
            })

    }

    // 初始加载数据
    showLoading();
    fetchGoodsInfo(getUserId(), ConfigDate).finally(() => {
        hideLoading();
    });
});